package com.yunjian.core.api;

import java.text.MessageFormat;
import java.util.List;
import java.util.*;

import com.yunjian.core.dto.SysUserDto;
import com.yunjian.core.entity.SysUserEntity;
import com.yunjian.core.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunjian.common.utils.Constant;
import com.yunjian.common.utils.DateUtils;
import com.yunjian.common.utils.JsonUtil;
import com.yunjian.common.utils.LanguageUtils;
import com.yunjian.core.dto.ResponseDto;
import com.yunjian.core.dto.SecurityContext;
import com.yunjian.core.entity.Account;
import com.yunjian.core.entity.MessageCenter;
import com.yunjian.core.service.IAccountService;
import com.yunjian.core.service.IMessageCenterService;
import com.yunjian.core.service.JPushService;

@RestController
@RequestMapping("/api/account")
public class AccountController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IAccountService accountServiceImpl;
    @Autowired
    private JPushService jPushServiceImpl;
    @Autowired
    private IMessageCenterService messageCenterServiceImpl;

    /**
     * 修改用户信息
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/modifyAccountInfo", method = RequestMethod.POST)
    @ResponseBody
    public ResponseDto modifyAccountInfo(@RequestBody Account param) {
        logger.info("修改用户信息{}", JsonUtil.toJsonString(param));
        return accountServiceImpl.modifyAccountInfo(param);
    }

    /**
     * 修改用户密码
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/modifyPassword", method = RequestMethod.POST)
    @ResponseBody
    public ResponseDto modifyPassword(@RequestBody Account param) {
        logger.info("修改用户密码{}", JsonUtil.toJsonString(param));
        if (StringUtils.isEmpty(param.getPassword())) {
            return new ResponseDto(Constant.PARMS_ERROR_CODE, null, LanguageUtils.getValueByKey("account.password.inNull"));
        }
        return accountServiceImpl.modifyPassword(param);
    }

    /**
     * 检查用户是否有可用的切割次数
     *
     * @return
     */
    @RequestMapping(value = "/checkUserCutTimes", method = RequestMethod.POST)
    @ResponseBody
    public ResponseDto checkUserCutTimes() {
        logger.info("检查用户是否有可用的切割次数");
        Account account = SecurityContext.getUserPrincipal();
        Account a = accountServiceImpl.getOne(new QueryWrapper<Account>().eq("id", account.getId()));
        if (a.getType() != 1 && a.getRemainTimes() == 0) {
            return new ResponseDto(Constant.SUCCESS_CODE, 0, Constant.SUCCESS_MESSAGE);
        } else {
            return new ResponseDto(Constant.SUCCESS_CODE, 1, Constant.SUCCESS_MESSAGE);
        }
    }

    /**
     * 切割成功通知用户
     */
    @PostMapping("/successNotify")
    public ResponseDto successNotify() {
        logger.info("切割成功通知用户");
        ResponseDto response = new ResponseDto(Constant.SUCCESS_CODE, null, Constant.SUCCESS_MESSAGE);
        try {
            //更新用户次数
            Account account = SecurityContext.getUserPrincipal();
            Account a = accountServiceImpl.getOne(new QueryWrapper<Account>().eq("id", account.getId()));
            //有限次数的用户不更新切割次数
            if (a.getType() != 1) {
                //更新设备次数
                a.setUseTimes(a.getUseTimes() + 1);
                a.setRemainTimes(a.getRemainTimes() - 1);
                accountServiceImpl.saveOrUpdate(a);
            }

            String title = LanguageUtils.getValueByKey("cut.success.notify");
            String content = "";
            if (a.getType() != 1) {
                content = MessageFormat.format(LanguageUtils.getValueByKey("cut.success.limit"), DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN), a.getRemainTimes());
                //content = "您在" + DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN) + "切膜成功，目前剩余可用次数为" + a.getRemainTimes() ;
            } else {
                content = MessageFormat.format(LanguageUtils.getValueByKey("cut.success.nolimit"), DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                //content = "您在" + DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN) + "切膜成功";
            }
            //消息存入数据库
            MessageCenter msg = new MessageCenter();
            msg.setAccountEmail(a.getEmail());
            msg.setAccountId(a.getId());
            msg.setContent(content);
            msg.setTitle(title);
            msg.setCreateTime(new Date());
            msg.setCreatorId(Long.parseLong(a.getDealerId() + ""));
            msg.setDeleteFlag(1);
            msg.setIsRead(0);
            msg.setUpdateTime(new Date());
            messageCenterServiceImpl.saveOrUpdate(msg);

            //极光推送
            List<String> alias = Arrays.asList(account.getEmail());
            Map<String, String> map = new HashMap<>();
            map.put("id", msg.getId() + "");
            jPushServiceImpl.pushAline(alias, title, content, map);
        } catch (Exception e) {
            logger.info("切割成功通知用户失败", e);
            return new ResponseDto(Constant.FAIL_CODE, null, LanguageUtils.getValueByKey("account.cutting.fail"));
        }
        return response;
    }

    @Autowired
    private SysUserService sysUserService;
    /**
     * 联系商家
     *
     * @return
     */
    @RequestMapping(value = "/Contact", method = RequestMethod.POST)
    @ResponseBody
    public ResponseDto Contact() {
        logger.info("联系商家");
        Account account = SecurityContext.getUserPrincipal();
        Account a = accountServiceImpl.getOne(new QueryWrapper<Account>().eq("id", account.getId()));
        SysUserEntity userEntity = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("user_id", a.getDealerId()));
        SysUserDto sysUserDto = new SysUserDto();
        BeanUtils.copyProperties(userEntity, sysUserDto);
        return new ResponseDto(Constant.SUCCESS_CODE, sysUserDto, Constant.SUCCESS_MESSAGE);
    }
}
